#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/12 23:44
# @Author  : lizhen
# @Site    : 
# @File    : cAlipay.py
# @Software: PyCharm
import ConfigParser
import traceback
import logging
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient, os
from alipay.aop.api.domain.AlipayTradePrecreateModel import AlipayTradePrecreateModel
from alipay.aop.api.domain.GoodsDetail import GoodsDetail
from alipay.aop.api.request.AlipayTradePrecreateRequest import AlipayTradePrecreateRequest
from alipay.aop.api.response.AlipayTradePrecreateResponse import AlipayTradePrecreateResponse
from utils.cQRCode import QRCodeDemo

logging.basicConfig(
    level=logging.ERROR,
    format='%(asctime)s %(levelname)s %(message)s',
    filemode='a', )
logger = logging.getLogger('')

if __name__ == '__main__':
    """
    设置配置，包括支付宝网关地址、app_id、应用私钥、支付宝公钥等，其他配置值可以查看AlipayClientConfig的定义。
    """
    alipay_cfg = os.environ['user_pswd']
    cp = ConfigParser.ConfigParser()
    cp.read(alipay_cfg)
    appid = cp.get('alipay', 'alipay_appid')
    appprivatekey_file = cp.get('alipay', 'alipay_appprivatekey')
    alipaypublickey_file = cp.get('alipay', 'alipay_alipaypublickey')
    selleruid = cp.get('alipay', 'alipay_selleruid')
    with open(unicode(appprivatekey_file, encoding='utf-8')) as f:
        appprivatekey = f.read()
    with open(unicode(alipaypublickey_file, encoding='utf-8')) as f:
        alipaypublickey = f.read()
    alipay_client_config = AlipayClientConfig()
    alipay_client_config.server_url = 'https://openapi.alipaydev.com/gateway.do'
    alipay_client_config.app_id = appid
    alipay_client_config.app_private_key = appprivatekey
    alipay_client_config.format = 'json'
    alipay_client_config.charset = 'utf-8'
    alipay_client_config.alipay_public_key = alipaypublickey
    alipay_client_config.sign_type = 'RSA2'
    """
    得到客户端对象。
    注意，一个alipay_client_config对象对应一个DefaultAlipayClient，定义DefaultAlipayClient对象后，alipay_client_config不得修改，如果想使用不同的配置，请定义不同的DefaultAlipayClient。
    logger参数用于打印日志，不传则不打印，建议传递。
    """
    client = DefaultAlipayClient(alipay_client_config=alipay_client_config, logger=logger)
    """
    系统接口示例：alipay.trade.pay
    """
    # 对照接口文档，构造请求对象
    model = AlipayTradePrecreateModel()
    model.out_trade_no = "20180510AB015"
    model.total_amount = "88.88"
    model.subject = "Iphone6 16G"

    model.seller_id = selleruid
    model.discountable_amount = 8.88
    model.body = "Iphone6 16G"
    model.operator_id = "yx_001"
    model.store_id = "NJ_001"
    # model.disable_pay_channels = "pcredit,moneyFund,debitCardExpress"
    model.enable_pay_channels = "pcredit,moneyFund,debitCardExpress"
    model.terminal_id = "NJ_T_001"
    model.timeout_express = "90m"
    model.merchant_order_no = "20161008001"
    model.business_params = {"data": "123"}
    model.qr_code_timeout_express = "90m"
    goods_list = list()
    goods1 = GoodsDetail()
    goods1.goods_id = "apple-01"
    goods1.goods_name = "ipad"
    goods1.quantity = 1
    goods1.price = 2000
    goods1.goods_category = "34543238"
    goods1.categories_tree = "124868003|126232002|126252004"
    goods1.body = "特价手机"
    goods1.show_url = "http://www.alipay.com/xxx.jpg"
    goods_list.append(goods1)
    model.goods_detail = goods_list
    request = AlipayTradePrecreateRequest(biz_model=model)
    response_content = None
    try:
        response_content = client.execute(request)
    except Exception as e:
        print(traceback.format_exc())
    if not response_content:
        print("failed execute")
    else:
        response = AlipayTradePrecreateResponse()
        # 解析响应结果
        response.parse_response_content(response_content)
        print(response.body)
        if response.is_success():
            # 如果业务成功，则通过respnse属性获取需要的值
            print("get response qr_code:" + response.qr_code)
            qd = QRCodeDemo()
            qd.gen_qrcode(response.qr_code, 'utils/ext/cQRCode/qrcode.png')
        else:
            # 如果业务失败，则从错误码中可以得知错误情况，具体错误码信息可以查看接口文档
            print(response.code + "," + response.msg + "," + response.sub_code + "," + response.sub_msg)
